import { ethers, network } from "hardhat";

async function main() {
  if (network.name !== "localhost" && network.name !== "hardhat") {
    throw new Error("Use --network localhost for this script");
  }

  const [deployer, operator, treasury, injector] = await ethers.getSigners();

  console.log("操作员账户:", operator.address);
  console.log("金库账户:", treasury.address);
  console.log("注入账户:", injector.address);

  // 获取已部署的合约地址
  // 注意：这些地址需要根据实际部署情况调整
  const CAKE_ADDRESS = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; // MockCake 地址
  const RNG_ADDRESS = "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512"; // MockRNG 地址
  const LOTTERY_ADDRESS = "0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"; // Lottery 地址

  console.log("使用合约地址:");
  console.log("CAKE:", CAKE_ADDRESS);
  console.log("RNG:", RNG_ADDRESS);
  console.log("Lottery:", LOTTERY_ADDRESS);

  // 获取彩票合约实例
  const lottery = await ethers.getContractAt("PancakeSwapLottery", LOTTERY_ADDRESS);

  // 检查当前彩票状态
  const currentLotteryId = await lottery.viewCurrentLotteryId();
  console.log("当前彩票ID:", currentLotteryId.toString());

  if (currentLotteryId.gt(0)) {
    const currentLottery = await lottery.viewLottery(currentLotteryId);
    console.log("当前彩票状态:", currentLottery.status);
    console.log("当前彩票开始时间:", new Date(currentLottery.startTime.toNumber() * 1000).toLocaleString());
    console.log("当前彩票结束时间:", new Date(currentLottery.endTime.toNumber() * 1000).toLocaleString());
  }

  // 彩票配置参数
  const now = Math.floor(Date.now() / 1000);
  const startTime = now; // 立即开始
  const endTime = now + (4 * 60 * 60); // 4小时后结束 (4小时 = 4 * 60 * 60秒)
  
  const priceTicketInCake = ethers.utils.parseEther("0.1"); // 0.1 CAKE per ticket
  const discountDivisor = 2000; // 折扣除数
  const treasuryFee = 500; // 5% 金库费用
  
  // 奖励分配 (必须总和为10000)
  const rewardsBreakdown = [
    2000, // 1个数字匹配: 20%
    1000, // 2个数字匹配: 10%
    1000, // 3个数字匹配: 10%
    2000, // 4个数字匹配: 20%
    2000, // 5个数字匹配: 20%
    2000, // 6个数字匹配: 20%
  ];

  console.log("\n=== 彩票配置 ===");
  console.log("开始时间:", new Date(startTime * 1000).toLocaleString());
  console.log("结束时间:", new Date(endTime * 1000).toLocaleString());
  console.log("持续时间:", (endTime - startTime) / 3600, "小时");
  console.log("票价:", ethers.utils.formatEther(priceTicketInCake), "CAKE");
  console.log("折扣除数:", discountDivisor);
  console.log("金库费用:", treasuryFee / 100, "%");
  console.log("奖励分配:", rewardsBreakdown.map((r, i) => `${i + 1}个数字: ${r / 100}%`).join(", "));

  // 检查奖励分配总和
  const totalRewards = rewardsBreakdown.reduce((sum, reward) => sum + reward, 0);
  if (totalRewards !== 10000) {
    throw new Error(`奖励分配总和必须为10000，当前为${totalRewards}`);
  }

  // 检查彩票长度是否在允许范围内
  const lotteryLength = endTime - startTime;
  const minLength = 4 * 60 * 60 - 5 * 60; // 4小时 - 5分钟
  const maxLength = 4 * 24 * 60 * 60 + 5 * 60; // 4天 + 5分钟
  
  if (lotteryLength < minLength || lotteryLength > maxLength) {
    throw new Error(`彩票长度必须在${minLength / 3600}小时到${maxLength / 3600}小时之间`);
  }

  // 检查票价是否在允许范围内
  const minPrice = ethers.utils.parseEther("0.005"); // 0.005 CAKE
  const maxPrice = ethers.utils.parseEther("50"); // 50 CAKE
  
  if (priceTicketInCake.lt(minPrice) || priceTicketInCake.gt(maxPrice)) {
    throw new Error(`票价必须在${ethers.utils.formatEther(minPrice)}到${ethers.utils.formatEther(maxPrice)} CAKE之间`);
  }

  console.log("\n=== 启动彩票 ===");
  
  try {
    // 启动彩票
    const tx = await lottery.connect(operator).startLottery(
      endTime,
      priceTicketInCake,
      discountDivisor,
      rewardsBreakdown,
      treasuryFee
    );

    console.log("交易哈希:", tx.hash);
    await tx.wait();
    
    console.log("✅ 彩票启动成功！");
    
    // 获取新的彩票信息
    const newLotteryId = await lottery.viewCurrentLotteryId();
    const newLottery = await lottery.viewLottery(newLotteryId);
    
    console.log("\n=== 新彩票信息 ===");
    console.log("彩票ID:", newLotteryId.toString());
    console.log("状态:", newLottery.status);
    console.log("开始时间:", new Date(newLottery.startTime.toNumber() * 1000).toLocaleString());
    console.log("结束时间:", new Date(newLottery.endTime.toNumber() * 1000).toLocaleString());
    console.log("票价:", ethers.utils.formatEther(newLottery.priceTicketInCake), "CAKE");
    console.log("已收集金额:", ethers.utils.formatEther(newLottery.amountCollectedInCake), "CAKE");
    
    console.log("\n🎉 彩票活动已开始！用户可以购买彩票了！");
    console.log("📅 活动结束时间:", new Date(endTime * 1000).toLocaleString());
    
  } catch (error) {
    console.error("❌ 启动彩票失败:", error);
    
    // 检查错误原因
    if (error.message.includes("Not time to start lottery")) {
      console.log("💡 提示: 当前彩票还未结束，需要等待当前彩票进入CLAIMABLE状态");
    } else if (error.message.includes("Lottery length outside of range")) {
      console.log("💡 提示: 彩票持续时间不在允许范围内 (4小时-5分钟 到 4天+5分钟)");
    } else if (error.message.includes("Outside of limits")) {
      console.log("💡 提示: 票价不在允许范围内 (0.005 到 50 CAKE)");
    } else if (error.message.includes("Discount divisor too low")) {
      console.log("💡 提示: 折扣除数太低 (必须 >= 300)");
    } else if (error.message.includes("Treasury fee too high")) {
      console.log("💡 提示: 金库费用太高 (必须 <= 3000 = 30%)");
    } else if (error.message.includes("Rewards must equal 10000")) {
      console.log("💡 提示: 奖励分配总和必须等于10000");
    } else if (error.message.includes("Not operator")) {
      console.log("💡 提示: 只有操作员可以启动彩票");
    }
  }
}

main().catch((e) => {
  console.error('启动彩票失败', e);
  process.exit(1);
});
